package com.kaibes.core.base.builder;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class JsonBuilder {

    private Map<String, Object> data = new HashMap<>();
    
    private JsonBuilder setKeyObject(String key, Object object) {
        data.put(key, object);
        return this;
    }
    private JsonBuilder setKeyObjectIgnoreNull(String key, Object object) {
        if (object != null) {
            data.put(key, object);
        }
        return this;
    }
    
    public JsonBuilder setKeyValue(String key, String value) {
        return setKeyObject(key, value);
    }
    public JsonBuilder setKeyValueIgnoreNull(String key, String value) {
        return setKeyObjectIgnoreNull(key, value);
    }
    
    public JsonBuilder setKeyValue(String key, Number value) {
        return setKeyObject(key, value);
    }
    public JsonBuilder setKeyValueIgnoreNull(String key, Number value) {
        return setKeyObjectIgnoreNull(key, value);
    }
    
    public String build() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        data.forEach((key, value)->{
            if (value instanceof String) {
                sb.append("\"").append(key).append("\"").append(":").append("\"").append(value).append("\"").append(",");
            } else {
                sb.append("\"").append(key).append("\"").append(":").append(value).append(",");
            }
        });
        if (sb.length()>2) {
            sb.deleteCharAt(sb.length()-1);
        }
        sb.append("}");
        return sb.toString();
    }
    
    @Override
    public String toString() {
        return build();
    }
    
    public static JsonBuilder newBuilder() {
        return new JsonBuilder();
    }
    
    public static JsonBuilder newBuilder(Object obj) {
        JsonBuilder builder = new JsonBuilder();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String key = field.getName();
            try {
                Object value = field.get(obj);
                builder.setKeyObject(key, value);
            } catch (IllegalArgumentException | IllegalAccessException e) {
            }
        }
        return builder;
    }
    
    public static JsonBuilder newBuilderIgnoreNull(Object obj) {
        JsonBuilder builder = new JsonBuilder();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            String key = field.getName();
            try {
                Object value = field.get(obj);
                if (value != null) {
                    builder.setKeyObject(key, value);
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
            }
        }
        return builder;
    }
    
}
